package leetcode.backtrace;

import java.util.ArrayList;
import java.util.List;

public class Lc216 {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combinationSum3(int k, int n) {
        getAns(1, 0, k, n, new ArrayList<>());
        return ans;
    }
    private void getAns(int start, int sum, int k, int n, List<Integer> list) {
        if (list.size() == k && sum == n) {
            ans.add(new ArrayList<>(list));
            return;
        }
        if (list.size() == k || sum == n || start > 9) return;
        for (int i = start; i <= 9; i++) {
            if (sum + i > n) break;
            if (sum + i == n) {
                if (list.size() == k - 1) {
                    list.add(i);
                    ans.add(new ArrayList<>(list));
                    list.remove(list.size() - 1);
                }
                break;
            }
            list.add(i);
            getAns(i + 1,sum + i, k, n, list);
            list.remove(list.size() - 1);
        }
    }

    public static void main(String[] args) {
        Lc216 lc216 = new Lc216();
        System.out.println(lc216.combinationSum3(4, 1));
    }

}
